package com.conversationboard.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.controller.banrequest.BanRequestData;
import com.conversationboard.database.BatchQueries;
import com.conversationboard.database.Database;
import com.conversationboard.model.User;

@WebServlet(name = "AdminViewBanRequestsControllerServlet", urlPatterns = "/Admin/AdminViewBanRequestsControllerServlet")
public class AdminViewBanRequestsControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 4783208094028262244L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {

			User user = User.get(request.getUserPrincipal().getName());

			if (!user.isSiteAdmin()) {
				return;
			}

			Connection connection = null;

			try {

				connection = Database.getConnection();

				PreparedStatement statement = connection.prepareStatement(BatchQueries.GET_BAN_REQUESTS);
				statement.execute();

				ResultSet resultSet = statement.getResultSet();

				List<BanRequestData> banRequests = new ArrayList<BanRequestData>();

				while (resultSet.next()) {

					BanRequestData banRequest = new BanRequestData();
					banRequest.setBanLoginId(resultSet.getString("banloginid"));
					banRequest.setOriginalDisplayName(resultSet.getString("originaldisplayname"));
					banRequest.setDisplayName(resultSet.getString("displayname"));
					banRequest.setTotal(resultSet.getInt("total"));

					banRequests.add(banRequest);
				}

				request.setAttribute("banRequests", banRequests);
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/Admin/view-ban-requests.jsp");

				dispatcher.forward(request, response);

			} finally {
				Database.close(connection);
			}
		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
